package org.flik.server.service;

import org.flik.client.login.service.LoginService;
import org.flik.server.ServerUtils;
import org.flik.server.bean.FlikUserBean;
import org.flik.server.dto.DuplicateUserExcecption;
import org.flik.server.dto.SessionInfo;
import org.flik.server.entity.FlikUser;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class LoginServiceImpl extends RemoteServiceServlet implements LoginService {

	@Override
	public Boolean login(String login, String password) {
		getThreadLocalRequest().getSession().invalidate();
		
		FlikUser loggedInFlikUser = ServerUtils.lookupBean(FlikUserBean.class).fetchUser(login, password);
//		boolean validLogin = login != null && login.equals("demo") && password != null && password.equals("demo"); 
		boolean validLogin = (loggedInFlikUser != null);
		if (validLogin){
			getThreadLocalRequest().getSession().setAttribute(ServerUtils.LOGIN_INFO, new SessionInfo(loggedInFlikUser.getUserName(), loggedInFlikUser.getFirstName(), loggedInFlikUser.getLastName(), loggedInFlikUser.getId()));	
		}
		return validLogin;
	}
	
	@Override
	public void createUser(String userName, String password, String firstName, String lastName, String email) throws DuplicateUserExcecption {
		FlikUserBean userBean = ServerUtils.lookupBean(FlikUserBean.class); 	
		if (userBean.isUserNameExist(userName))
			throw new DuplicateUserExcecption("Duplicate user: " + userName);
		else 
			userBean.createUser(userName, password, firstName, lastName, email);
	}

}
